package com.ygou.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.tools.ant.taskdefs.condition.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ygou.pojo.Admininfo;
import com.ygou.pojo.UserAddress;
import com.ygou.pojo.Users;
import com.ygou.service.UserAddressService;
import com.ygou.service.UsersService;
import com.ygou.utils.AppendContentToFile;
import com.ygou.utils.FileUDUtil;
import com.ygou.utils.MD5Util;
import com.ygou.utils.Tools;

@Controller
@RequestMapping(value="/users")
@SessionAttributes(value={"users"})
public class UsersController {
	@Autowired
	UsersService usersService;
	@Autowired
	UserAddressService userAddressService;
	@Autowired
	HttpServletResponse response;
	@RequestMapping(value="/insertUser")
	public void insertUser(HttpSession session,Users user,HttpServletRequest request) throws IOException, AddressException, NoSuchAlgorithmException, MessagingException{
		PrintWriter out=response.getWriter();
		response.setContentType("text/html;charset=utf-8");
		user.setLastip(Tools.getLocalIp(request));
		if(usersService.insert(user)){
			/*******写入日志******/
			Admininfo admins= (Admininfo)session.getAttribute("admin");
			int id=100;
			if(admins!=null){
				id=admins.getAdminid();
			}
			AppendContentToFile.fileLogPrint(id+"", "管理员添一个用户");
			/*******END写入日志******/
			out.print("<script>" +
					"alert('添加成功');" +
					"location.href='/users/selectbyExample';" +
					"</script>");
		}else{
			out.print("<script>" +
					"alert('添加失败');" +
					"history.back();"+
					"</script>");
		}
	}
	//根据条件查询
	@RequestMapping(value="/selectbyExample")
	public String findByWhere(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="10") Integer pageSize,String name,String time,ModelMap model){
		PageHelper.startPage(currPageNo, pageSize);
		List<Users> list=usersService.findByWhere(name,time,null); 
		PageInfo<Users> pages=new PageInfo<Users>(list,pageSize);
		model.put("name",name);
		model.put("time",time);
		model.put("pageInfo",pages);
		return "/admin/user_list";
	}

	//根据主键查询
	@RequestMapping(value="/selectByPrimaryKey")
	public String selectByPrimaryKey(Integer userid,String type,ModelMap model){
		Users users=usersService.selectByPrimaryKey(userid);
		model.put("users",users==null?"":users);
		String path="";
		if("backer".equals(type)){
			path="/admin/member-show";
		}else if("top-cont".equals(type)){
			path="/setAvatar";
		}
		return path;
	}
	
	//根据主键修改状态
	@RequestMapping(value="/updateByPrimaryKeySelective",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean updateByPrimaryKeySelective(HttpSession session,Integer userid,Integer userStaus) throws IOException{
		Users users=usersService.selectByPrimaryKey(userid);
		if(userStaus==0){//0冻结
			users.setUserstaus((byte)1);
		}else{
			users.setUserstaus((byte)0);
		}
		/*******写入日志******/
		Admininfo admins= (Admininfo)session.getAttribute("admin");
		int id=100;
		if(admins!=null){
			id=admins.getAdminid();
		}
		AppendContentToFile.fileLogPrint(id+"", "管理员对"+userid+"用户进行了冻结/解冻");
		/*******END写入日志******/
		return usersService.updateByPrimaryKeySelective(users);
	}
	
	/**
	 * 登录
	 * @param user
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/login",produces="application/json;charset=UTF-8")
	public @ResponseBody Users login(String account,HttpServletRequest reuqest,String loginpwd){
		//判断是邮箱还是手机号的正则表达式  
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";  
        String ph = "^[1][34578]\\d{9}$";
		Map<String,Object> map=new HashMap<>();
		if(account.matches(em)){
			map.put("userEmail",account);
		}else if(account.matches(ph)){
			map.put("userPhone",account);
		}else{
			map.put("userName",account);
		}
		map.put("loginPwd",MD5Util.getMd5(loginpwd));
		Users users=usersService.findUserInfoByWhere(map);
		if(users!=null) reuqest.getSession().setAttribute("user",users);
		return users;
	}
	
	/**
	 * 前台注册功能
	 * @return
	 * @throws MessagingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws AddressException 
	 */
	@RequestMapping(value="/register",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean register(Users user,HttpServletRequest request) throws AddressException, NoSuchAlgorithmException, MessagingException{
		user.setLastip(Tools.getLocalIp(request));
		return usersService.insert(user);
	}
	
	/**
	 * 注册判断
	 * 
	 */
	@RequestMapping(value="/checkAccount",produces="application/json;charset=UTF-8")
	 public @ResponseBody boolean checkEmail(String useremail,String username){
		 Map<String, Object> map = new HashMap<>();
		 if(useremail!=null&&!"".equals(useremail)){
			 map.put("userEmail", useremail);
		 }else{
			 map.put("userName", username);
		 }
		 return usersService.findUserInfoByWhere(map) != null;
	 }

	/**
	 * 修改头像
	 * @param userid
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/updUserPhoto",produces="application/json;charset=UTF-8")
	public @ResponseBody int updUserPhoto(Integer userid,HttpServletRequest request){
		Users user=usersService.selectByPrimaryKey(userid);
		//设置图片上传路径
		FileUDUtil.UPLOADDIR="filecontent/userimg/";
		//执行上传 
		int result=FileUDUtil.upload(request);
		if(result==0){
			user.setUserphoto(FileUDUtil.FILENAME.get(0));
		}
		if(!usersService.updateByPrimaryKey(user)) result=-1;
		setSesssionAttribute(request.getSession(), user);
		return result;
	}
	/**
	 * 修改登录密码
	 * @param user
	 * @param newpwd
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/updLoginPwd",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean updLoginPwd (Users user,String newpwd,HttpSession session){
		boolean flag=false;
		Users u=usersService.selectByPrimaryKey(user.getUserid());
		if(u.getLoginpwd().equals(MD5Util.getMd5(user.getLoginpwd()))){
			String pwd=MD5Util.getMd5(newpwd);
			u.setLoginpwd(pwd);
			user.setLoginpwd(pwd);
			setSesssionAttribute(session,u);
			flag=usersService.updateByPrimaryKey(user);
		}
		return flag;
	}
	
	/**
	 * 修改支付密码
	 * @param user
	 * @param newpwd
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/updPayPwd",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean updPayPwd (Users user,String newPayPwd,HttpSession session){
		boolean flag=false;
		Users u=usersService.selectByPrimaryKey(user.getUserid());
		if(u.getPaypwd()!=null&&!"".equals(u.getPaypwd())){
			if(u.getPaypwd().equals(MD5Util.getMd5(user.getPaypwd()))){
				String paypwd=MD5Util.getMd5(newPayPwd);
				u.setPaypwd(paypwd);
				user.setPaypwd(paypwd);
				setSesssionAttribute(session,u);
				flag=usersService.updateByPrimaryKey(user);
			}
		}else{
			String paypwd=MD5Util.getMd5(user.getPaypwd());
			u.setPaypwd(paypwd);
			user.setPaypwd(paypwd);
			setSesssionAttribute(session,u);
			flag=usersService.updateByPrimaryKey(user);
		}
		return flag;
	}
	/**
	 * 校验支付密码正确性
	 * @param username
	 * @param paypwd
	 * @return
	 */
	@RequestMapping(value="/checkPayPwd",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean checkPayPwd(String username,String paypwd){
		Map<String,Object> map=new HashMap<>();
		map.put("userName", username);
		map.put("payPwd",MD5Util.getMd5(paypwd));
		return usersService.findUserInfoByWhere(map)!=null;
	}
	/**
	 * 校验用户有没有收货地址
	 */
	@RequestMapping(value="/checkAddress/{userid}",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean checkAddress(@PathVariable Integer userid){
		List<UserAddress> address=userAddressService.findAddressByUId(userid);
		if(address==null || address.size()==0){
			return false;
		}
		return true;
	}
	
	/**
	 * 修改用户基本信息
	 * @param user
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/updUserInfo",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean updUserInfo (Users user,HttpSession session){
		setSesssionAttribute(session, user);
		return usersService.updateByPrimaryKeySelective(user);
	}
	
	//公共重置user对象session
	public void setSesssionAttribute(HttpSession session,Users user){
		session.setAttribute("user",user);
	}
	/**
	 * 退出登录
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/exit")
	public String exit(HttpSession session){
		session.removeAttribute("user");
		return "redirect:/index.jsp";
	} 
}
